<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-03-23
 * Time: 16:21
 */
namespace app\common\model;
use app\common\controller\Upload;
use app\common\extend\Cxexp;
use think\Db;
use think\db\Query;
use think\Model;

class Article extends Model{
    // 开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $insert = ['addtime','addip'];
    protected $update = ['edittime','editip'];
    protected $type = [
        'addtime'    => 'timestamp',
        'edittime'    => 'timestamp',
    ];
    // 定义时间戳字段名
    protected $createTime = 'addtime';
    protected $updateTime = 'edittime';
    protected function setAddipAttr(){
        return request()->ip();
    }
    protected function setEditipAttr(){
        return request()->ip();
    }
    // 启用状态
    protected function getStatusIconAttr($value,$data){
        $status = [ 0 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/see').'" class="cx-click" data-type="sestatus"><i class="cx-icon cx-icon-iconset0187 t-gray"></i></a>',1 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/see').'" class="cx-click" data-type="sestatus"><i class="cx-icon cx-icon-zhengchang t-green"></i></a>',2 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/see').'" class="button button-S cx-click bg-green" data-type="sestatus"><i class="cx-icon cx-icon-huanyuanmulu"></i> 还原</a>'];
        return $status[$data['status']];
    }
    // 启用状态
    protected function getJianIconAttr($value,$data){
        $jian = [ 0 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/jian').'" class="cx-click" data-type="sestatus"><i class="cx-icon cx-icon-good t-gray"></i></a>',1 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/jian').'" class="cx-click" data-type="sestatus"><i class="cx-icon cx-icon-good t-red"></i></a>'];
        return $jian[$data['jian']];
    }
    // 启用状态
    protected function getTopIconAttr($value,$data){
        $top = [ 0 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/top').'" class="cx-click" data-type="sestatus"><i class="cx-icon cx-icon-stick_icon t-gray"></i></a>',1 => '<a data-id="'.$data['aid'].'" data-href="'.url('Article/top').'" class="cx-click" data-type="sestatus"><i class="cx-icon cx-icon-stick_icon t-red"></i></a>'];
        return $top[$data['top']];
    }
    // 关联用户资料表
    public function articledb(){
        return $this->hasOne('ArtCont','aid','aid');
    }
    //  获取栏目基本信息
    public function basi($data){
        $data['template'] = unserialize($data['template']);
        if(!empty($data['template'])){
            foreach ($data['template'] as $k => $v){
                $data[$k.'temp'] = $v;
            }
        }
        unset($data['template']);
        return $data;
    }
    /**
     * @param $data 请求参数 mid,fid,order,num,page,及附加参数
     * @return null
     */
    public function get_list($data){
        $mid = empty($data['mid'])&&!isset($data['mid']) ? null:$data['mid'];
        $num = empty($data['num']) ? '20' : $data['num'];
        $fid = empty($data['fid']) ? null : $data['fid'];
        $uid = empty($data['uid']) ? null : $data['uid'];
        $order = empty($data['order']) ? '0' : $data['order'];
        $page = empty($data['page']) ? '1' : $data['page'];
        //  判断需要查询的数据表
        $getlist = null;
        $ora = $orb = null;
        //  构造查询语句
        $query = new Query();
        $query = $query->name('article');
        if(!empty($mid) || isset($mid)){
            if($mid == '0'){
                $query = $query->where("mid","0");
            }else{
                $ora = 'a.';
                $orb = 'b.';
                $query = $query->alias('a')->join("article_content_{$mid} b",'b.aid = a.aid');
            }
            $map['mid'] = $mid;
        }
        if(!empty($uid)){
            $query = $query->where("{$ora}uid","{$uid}");
            $map['uid'] = $uid;
        }
        //  判断需要查询的栏目
        if(!empty($fid)){
            //  查询栏目类型
            $partmodel = new Part();
            $part = $partmodel->onepart($fid);
            if($part['class'] == '0'){
                $parts = $partmodel->largelist($part['id']);
                $fids = array();
                foreach ($parts as $k => $v){
                    $fids[] = $v['id'];
                }
                $fids = implode(',',$fids);
                $query = $query->where("{$ora}fid",'in',"{$fids}");
                $map['fid'] = array('in',$fids);
            }else{
                $query = $query->where("{$ora}fid","{$fid}");
                $map['fid'] = $fid;
            }
        }
        //  判断排序方式
        if(is_numeric($order)){
            switch ($order){
                case '0':
                    $order = "{$ora}top desc,{$ora}jian desc,{$ora}aid desc";
                    break;
                case '1':
                    $order = "{$ora}addtime desc";
                    break;
                case '2':
                    $order = "{$ora}addtime asc";
                    break;
                case '3':
                    $order = "{$ora}hist desc";
                    break;
                case '4':
                    $order = "{$ora}seetime desc";
                    break;
            }
        }else{
            $order = "{$orb}{$order} desc";
        }
        $map['status'] = '1';
        $query = $query->where("{$ora}status",'1')->order($order)->limit($num)->page($page);
        //  查询所有数量
        $_listdata = Db::select($query);
        //  查询所有数据
        $listmun = $this->where($map)->count();
        $pages = ceil($listmun/$num);
        //  格式化查询到的数据
        $listdata = null;
        if(!empty($_listdata)){
            foreach ($_listdata as $k => $v){
                $listdata[$k] = $this->get_onedata($v);
            }
        }
        $res = array(
            'list' => $listdata,
            'pages' => $pages,
            'page' => $page,
            'pagenum' => $listmun,
        );
        return $res;
    }
    /**
     * 处理api数据
     */
    public function get_onedata($data,$partbase=''){
        unset($data['id']);
        $webdb = webdb();
        if(!is_array($data)){
            $data = $data->toArray();
        }
        //  读取模型信息并处理数据
        if($data['mid'] !== 0){
            $cxexp = new Cxexp();
            $data = $cxexp->get_form($data);
        }
        $data['futitle'] = $data['title'] = preg_replace('/<([^<]*)>/is',"",$data['title']);
        if(!empty($partbase['maxnum']) || isset($partbase['maxnum'])){
            $data['title'] = get_word($data['title'],$partbase['maxnum']);
        }
        $part = \model('Part')->onepart($data['fid']);
        $data['partname'] = $part['title'];
        //  获取发布人信息
        $userdata = \model('UserData')->where('uid',$data['uid'])->find();
        if(!empty($userdata)){
            $userdata = $userdata->toArray();
        }
        $data['username'] = empty($userdata['uniname']) ? $userdata['username']:$userdata['uniname'];
        $data['uicon'] = empty($userdata['uicon']) ? null:'/'.$webdb['updir'].'/'.$userdata['uicon'];
        //  图片
        if(!empty($data['picurl'])){
            $picurl = explode('/',$data['picurl']);
            $data['picurl3'] = '/'.$webdb['updir'].'/'.$data['picurl'];		//1:1的图
            $data['picurl'] = '/'.$webdb['updir'].'/'.$picurl['0']."/1x1_{$picurl['1']}";		//1:1的图
            $data['picurl1'] = '/'.$webdb['updir'].'/'.$picurl['0']."/3x4_{$picurl['1']}";		//1:1的图
            $data['picurl2'] = '/'.$webdb['updir'].'/'.$picurl['0']."/4x3_{$picurl['1']}";		//1:1的图
        }else{
            $data['picurl1'] = $data['picurl2'] = $data['picurl3'] = "";
        }
        $data['url']= url('Article/index',array('aid'=>$data['aid']));
        //  获取内容简介
        if(!isset($data['description']) || empty($data['description'])){
            $data['description'] = $data['contents'] = model('ArtCont')->where('aid',$data['aid'])->value('content');
        }
        $data['description'] = str_replace(PHP_EOL, '', $data['description']);
        $data['description'] = preg_replace('/<([^<]*)>/is',"",$data['description']);
        $data['description'] = preg_replace('/ |　|&nbsp;/is',"",$data['description']);	//把多余的空格去除掉
        if(!empty($partbase['contnum'])){
            $data['description'] = get_word($data['description'],$partbase['contnum']);
        }else{
            $data['description'] = get_word($data['description'],'300',false);
        }
        $upmodel = new Upload();
        foreach ($data as $key => $val){
            $data[$key] = $upmodel->editadd($val,false,$webdb['www_url']);
        }
        $addtime = $data['addtime'];
        if(!is_numeric($addtime)){
            $addtime = strtotime($data['addtime']);
        }
        $data['time_Y']=date("Y",$addtime);
        $data['time_y']=date("y",$addtime);
        $data['time_m']=date("m",$addtime);
        $data['time_d']=date("d",$addtime);
        $data['time_H']=date("H",$addtime);
        $data['time_i']=date("i",$addtime);
        $data['time_s']=date("s",$addtime);
        return $data;
    }
    //  获取附加表字段
    public function futabel($mid){
        $tabelname = config('database.prefix').'article_content_'.$mid;
        $fields = Db::query("DESC $tabelname");
        $arr = '';
        foreach ($fields as $v){
            $arr[] = $v['Field'];
        }
        return $arr;
    }

}